package com.ddwl.wallet.dao;

import com.ddwl.common.constant.DistConstant;
import com.ddwl.common.constant.DistTypeEnum;
import com.ddwl.common.dao.TkDao;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.schema.bo.order.QueryUserDistOrderBo;
import com.ddwl.schema.bo.order.SubAgentDistOrderBo;
import com.ddwl.schema.bo.wallet.QueryWalletMainReportBo;
import com.ddwl.schema.util.DateUtil;
import com.ddwl.schema.vo.wallet.AgentDistStatisticsDto;
import com.ddwl.wallet.dao.dto.DistOrderStatisticsDto;
import com.ddwl.wallet.dao.dto.DistOrderStatisticsQueryDto;
import com.ddwl.wallet.dao.dto.DistOrderTotalDto;
import com.ddwl.wallet.dao.dto.UserWalletMainReportDto;
import com.ddwl.wallet.dao.mapper.OrderMapper;
import com.ddwl.wallet.dao.model.DistOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

/**
 * 分润金额记录表(Order)数据处理
 *
 * @author zach
 * @since 2020-07-22 12:44:36
 */
@Repository
@Slf4j
public class OrderDao extends TkDao<OrderMapper, DistOrder> {


    /**
     * 查询用户预估收入
     *
     * @param bo
     * @return
     */
    public List<DistOrderStatisticsDto> queryUserPreIncome(DistOrderStatisticsQueryDto bo) {
        return baseMapper.queryOrderReport(bo);
    }

    /**
     * 查询用户上个月预估收入
     *
     * @param userId
     * @return
     */
    public List<DistOrderStatisticsDto> queryUserBeforeMonth(String userId) {
        DistOrderStatisticsQueryDto query = new DistOrderStatisticsQueryDto();
        query.setUserId(userId);
        query.setStartTime(DateUtil.getBeforeMonthStart());
        query.setEndTime(DateUtil.getFirstDayMonth(Instant.now()));
        return baseMapper.queryOrderMonthlyReport(query);
    }

    /**
     * 查询用户当前月月预估收入
     *
     * @param userId
     * @returnt
     */
    public List<DistOrderStatisticsDto> queryUserAtMonth(String userId) {
        DistOrderStatisticsQueryDto query = new DistOrderStatisticsQueryDto();
        query.setUserId(userId);
        query.setStartTime(DateUtil.getFirstDayMonth(Instant.now()));
        query.setEndTime(DateUtil.getFirstDayAfterMonth(Instant.now()));
        return baseMapper.queryOrderMonthlyReport(query);
    }

    /**
     * 查询用户分销的订单
     *
     * @param bo
     * @return
     */
    public List<DistOrder> queryDistOrder(QueryUserDistOrderBo bo) {
        Example example = getExample();
        example.and().andEqualTo("orderStatus", bo.getStatus())
                .andIn("orderStatus", bo.getStatusList())
                .andGreaterThanOrEqualTo("payTime", bo.getStartTime())
                .andLessThan("payTime", bo.getEndTime())
                .andLike("orderId", MySqlUtil.allLike(bo.getOrderId()));
/*        example.and().orEqualTo("distUserId",bo.getUserId())
                .orEqualTo("regionUserId",bo.getUserId());*/
        example.and().andEqualTo("distUserId", bo.getUserId())
                .andLike("distUserName", MySqlUtil.allLike(bo.getDistUserName()))
                .andLike("distUserTel", MySqlUtil.allLike(bo.getDistUserTel()))
                .andEqualTo("distUserId", bo.getDistUserId())
        ;
        if (bo.getIsAfterSale() != null && bo.getIsAfterSale() == 0) {
            example.and().andCondition(" is_after_sale = 0 or is_after_sale is NULL ");
        } else if (bo.getIsAfterSale() != null && bo.getIsAfterSale() == 1) {
            example.and().andEqualTo("isAfterSale", 1);
        }
        if (bo.getType() == null) {
            bo.setType(DistTypeEnum.PERSONAL.getType());
            bo.setType(DistTypeEnum.SHOP.getType());
        }
        if (bo.getType() == 3) {
            List<Integer> list = new ArrayList<>();
            list.add(DistTypeEnum.REGION.getType());
            list.add(DistTypeEnum.TOP.getType());
            example.and().andIn("distType", list);
        } else if (bo.getType() == 2) {
            List<Integer> list = new ArrayList<>();
            list.add(DistTypeEnum.IMMEDIATE.getType());
            list.add(DistTypeEnum.INDIRECT.getType());
            list.add(DistTypeEnum.USER_AGENT_PROFIT.getType());
            list.add(DistTypeEnum.AGENT_ITEM_PROFIT.getType());
            list.add(DistTypeEnum.PERSONAL_AGENT_PROFIT.getType());
            list.add(DistTypeEnum.STORE_AGENT_PROFIT.getType());
            list.add(DistTypeEnum.ZONE_AGENT_PROFIT.getType());
            example.and().andIn("distType", list);
        } else if (bo.getType() == 7) {
            List<Integer> list = new ArrayList<>();
            list.add(DistTypeEnum.PERSONAL.getType());
            list.add(DistTypeEnum.IMMEDIATE.getType());
            list.add(DistTypeEnum.INDIRECT.getType());
            list.add(DistTypeEnum.REGION.getType());
            list.add(DistTypeEnum.TOP.getType());
            list.add(DistTypeEnum.SHOP.getType());
            list.add(DistTypeEnum.PERSONAL_AGENT_PROFIT.getType());
            list.add(DistTypeEnum.STORE_AGENT_PROFIT.getType());
            list.add(DistTypeEnum.ZONE_AGENT_PROFIT.getType());
            example.and().andIn("distType", list);
        } else {
            example.and().andEqualTo("distType", 1);
        }
        return baseMapper.selectByExample(example);
    }

    /**
     * 查询用户分销的订单
     *
     * @param bo
     * @return
     */
    public List<DistOrder> queryDistOrderForConsole(QueryUserDistOrderBo bo) {
        return baseMapper.queryDistOrderForConsole(bo);
    }

    /**
     * 查询用户分销的订单总数总金额
     *
     * @param bo
     * @return
     */
    public DistOrderTotalDto queryDistOrderTotalForConsole(QueryUserDistOrderBo bo) {
        return baseMapper.queryDistOrderTotalForConsole(bo);
    }


    /**
     * 查询已过售后期限的订单
     *
     * @return
     */
    public List<DistOrder> queryOverAfterSaleConfirmOrder(Integer afterSaleDate) {
        Example example = getExample();
        example.and().andEqualTo("orderStatus", DistConstant.DistOrderStatus.TAKE.getCode())
                .andEqualTo("numberRefund", 0)
                //.andGreaterThanOrEqualTo("confirmTime",DateUtil.getTimesMorning(-(afterSaleDate+1)))
                .andLessThan("confirmTime", DateUtil.getTimesNight(-(afterSaleDate + 1)));
        example.and().andNotEqualTo("isAfterSale", 1)
                .orIsNull("isAfterSale");
        return baseMapper.selectByExample(example);
    }

    /**
     * 查询开门店佣金
     *
     * @return
     */
    public List<DistOrder> queryShopApproveOrder(Integer day) {
        Example example = getExample();
        example.and().andEqualTo("orderStatus", DistConstant.DistOrderStatus.TAKE.getCode())
                .andEqualTo("type", DistConstant.DistrConfigType.SHOP.getCode())
                .andGreaterThan("gmtCreated", DateUtil.getTimesNight(day));
        return baseMapper.selectByExample(example);
    }

    /**
     * 查询根据订单号查询分销订单
     *
     * @param orderId
     * @return
     */
    public DistOrder queryDistOrderByOrderId(String orderId) {
        DistOrder distOrder = new DistOrder();
        distOrder.setOrderId(orderId);
        return selectOne(distOrder);
    }


    /**
     * 查询根据订单号查询分销订单
     *
     * @param orderId
     * @return
     */
    public List<DistOrder> queryDistOrderListByOrderId(String orderId) {
        DistOrder distOrder = new DistOrder();
        distOrder.setOrderId(orderId);
        return select(distOrder);
    }

    public void confirmOrder(String orderId, Instant confirmTime) {
        DistOrder distOrder = new DistOrder();
        distOrder.setOrderStatus(DistConstant.DistOrderStatus.TAKE.getCode());
        distOrder.setConfirmTime(confirmTime);
        distOrder.setGmtModified(Instant.now());
        Example example = new Example(DistOrder.class);
        example.and().andEqualTo("orderId", orderId);
        baseMapper.updateByExampleSelective(distOrder, example);
    }


    /**
     * 修改分销订单售后状态
     *
     * @param orderId
     * @return
     */
    public void refundDistOrder(String orderId, String spuId) {
        DistOrder distOrder = new DistOrder();
        distOrder.setIsAfterSale(1);
        distOrder.setGmtModified(Instant.now());
        Example example = new Example(DistOrder.class);
        example.and().andEqualTo("orderId", orderId)
                .andEqualTo("spuId", spuId)
                .andNotEqualTo("distType", DistTypeEnum.SHOP.getType());
        Integer i = baseMapper.updateByExampleSelective(distOrder, example);
        addNumberRefund(orderId, spuId);
    }

    /**
     * 查询可结算的分销订单
     *
     * @param orderId
     */
    public List<DistOrder> queryPayOffDistOrder(String orderId) {
        Example example = new Example(DistOrder.class);
        example.and().andEqualTo("orderId", orderId)
                .andEqualTo("numberRefund", 0)
                .andEqualTo("orderStatus", DistConstant.DistOrderStatus.TAKE.getCode())
                .andNotEqualTo("distType", DistTypeEnum.SHOP.getType());
        return baseMapper.selectByExample(example);
    }

    /**
     * 查询未结算的分销订单
     *
     * @param orderId
     */
    public List<DistOrder> queryNoPayOffDistOrder(String orderId) {
        Example example = new Example(DistOrder.class);
        example.and().andEqualTo("orderId", orderId)
                .andEqualTo("numberRefund", 0)
                .andNotEqualTo("orderStatus", DistConstant.DistOrderStatus.CLOSE.getCode())
                .andNotEqualTo("distType", DistTypeEnum.SHOP.getType());
        return baseMapper.selectByExample(example);
    }

    public List<DistOrder> queryDistOrder(String orderId, String spuId) {
        DistOrder distOrder = new DistOrder();
        distOrder.setOrderId(orderId);
        distOrder.setSpuId(spuId);
        return select(distOrder);
    }

    public DistOrder queryDistOrder(String orderId, String spuId, Integer distType) {
        DistOrder distOrder = new DistOrder();
        distOrder.setOrderId(orderId);
        distOrder.setSpuId(spuId);
        distOrder.setDistType(distType);
        return selectOne(distOrder);
    }


    public void copyInsert(DistOrder distOrder) {
        baseMapper.insert(distOrder);
    }


    public UserWalletMainReportDto queryWalletMainReport(QueryWalletMainReportBo bo) {
        return baseMapper.queryWalletMainReport(bo);
    }

    public void batchUpdateUser(List<DistOrder> list) {
        baseMapper.batchUpdateUser(list);
    }

    public void addNumberRefund(String orderId, String spuId) {
        baseMapper.addNumberRefund(orderId, spuId);
    }

    public void minusNumberRefund(String orderId, String spuId) {
        baseMapper.minusNumberRefund(orderId, spuId);
    }

    public List<DistOrder> querySubAgentDistOrder(SubAgentDistOrderBo bo, List<String> orderIds) {
        Example example = getExample();
        example.and().andEqualTo("source", bo.getSource())
                .andIn("orderStatus", bo.getStatusList())
                .andEqualTo("distUserId", bo.getUserId())
                .andIn("orderId", orderIds);
        return baseMapper.selectByExample(example);
    }

    public List<String> distOrderGroupByOrderId(SubAgentDistOrderBo param) {
        return baseMapper.distOrderGroupByOrderId(param);
    }

    public List<AgentDistStatisticsDto> getAgentDistStatistics(String distUserId, List<String> sources) {
        return baseMapper.getAgentDistStatistics(distUserId, sources);
    }
}